<template>
  <div class="app-container">
    <el-card class="filter-card">
      <div class="filter-container">
        <el-form :inline="true" :model="queryParams" class="search-form">
          <el-form-item label="育苗点">
            <el-select 
              v-model="queryParams.deptId" 
              placeholder="请选择育苗点"
              clearable
              filterable
              style="width: 300px"
              @change="handleSearch"
            >
              <el-option
                v-for="item in nurseryOptions"
                :key="item.deptId"
                :label="item.deptName"
                :value="item.deptId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="日期范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              style="width: 350px"
              @change="handleSearch"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            <el-button type="info" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-title">总计划条数</div>
          <div class="stats-value">{{ totalPlans }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card" :body-style="{ background: '#409EFF' }">
          <div class="stats-title">已分配，未开始育苗（亩）</div>
          <div class="stats-value">{{ allocatedCount }}</div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover" class="stats-card" :body-style="{ background: '#fdf6ec' }">
          <div class="stats-title">育苗中数量（亩）</div>
          <div class="stats-value">{{ inProgressCount }}</div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover" class="stats-card" :body-style="{ background: '#f0f9eb' }">
          <div class="stats-title">已完成数量（亩）</div>
          <div class="stats-value">{{ completedCount }}</div>
        </el-card>
      </el-col>

    </el-row>

    <!-- 折线图 -->
    <el-card class="chart-card">
      <div class="chart-wrapper">
        <echarts-card
          v-if="allocationList.length > 0"
          title="育苗任务趋势"
          :options="chartOptions"
          height="400"
          class="echarts-container"
        />
        <div v-else class="no-data">
          <i class="el-icon-data-line"></i>
          <p>暂无数据</p>
        </div>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="allocationList"
        border
        style="width: 100%"
      >
        <el-table-column prop="deptName" label="育苗点" min-width="200" show-overflow-tooltip />
        <el-table-column prop="growerName" label="烟农" width="120" />
        <el-table-column prop="planId" label="计划编号" width="100" />
        <el-table-column prop="nurseryDate" label="育苗日期" width="120" />
        <el-table-column prop="quantity" label="数量" width="100" align="right" />
        <el-table-column prop="statusDesc" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.statusDesc }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import request from '@/utils/request'
import EchartsCard from '@/components/EchartsCard.vue'

export default {
  name: 'NurseryStats',
  components: {
    EchartsCard
  },
  data() {
    return {
      loading: false,
      queryParams: {
        deptId: undefined,
        startDate: undefined,
        endDate: undefined
      },
      dateRange: [],
      nurseryOptions: [],
      allocationList: []
    }
  },
  computed: {
    // 计算总计划数
    totalPlans() {
      return this.allocationList.length
    },
    // 计算已分配数量
    allocatedCount() {
      return this.allocationList.filter(item => item.status === 2)
        .reduce((sum, item) => sum + item.quantity, 0)
    },
    // 计算育苗中数量
    inProgressCount() {
      return this.allocationList.filter(item => item.status === 3)
        .reduce((sum, item) => sum + item.quantity, 0)
    },
    // 计算已完成数量
    completedCount() {
      return this.allocationList.filter(item => item.status === 4)
        .reduce((sum, item) => sum + item.quantity, 0)
    },
    // 图表配置
    chartOptions() {
      // 获取所有不重复的日期并排序
      const dates = [...new Set(this.allocationList.map(item => item.nurseryDate))].sort()
      
      // 按状态和日期统计数量
      const statusData = {
        allocated: new Array(dates.length).fill(0),
        inProgress: new Array(dates.length).fill(0),
        completed: new Array(dates.length).fill(0)
      }
      
      // 统计每个日期各状态的数量
      this.allocationList.forEach(item => {
        const dateIndex = dates.indexOf(item.nurseryDate)
        if (dateIndex !== -1) {
          switch (item.status) {
            case 2: // 已分配
              statusData.allocated[dateIndex] += item.quantity
              break
            case 3: // 育苗中
              statusData.inProgress[dateIndex] += item.quantity
              break
            case 4: // 已完成
              statusData.completed[dateIndex] += item.quantity
              break
          }
        }
      })

      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            let result = params[0].axisValue + '<br/>'
            params.forEach(param => {
              const marker = param.marker
              const seriesName = param.seriesName
              const value = param.value
              result += marker + seriesName + ': ' + value + ' 亩<br/>'
            })
            return result
          }
        },
        legend: {
          data: ['已分配', '育苗中', '已完成'],
          bottom: 0
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          top: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisLabel: {
            rotate: 45,
            formatter: function(value) {
              return value.substring(5) // 只显示月-日
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '数量(亩)',
          minInterval: 1,
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        series: [
          {
            name: '已分配',
            type: 'line',
            data: statusData.allocated,
            itemStyle: {
              color: '#409EFF'
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0,
                  color: 'rgba(64,158,255,0.2)'
                }, {
                  offset: 1,
                  color: 'rgba(64,158,255,0)'
                }]
              }
            },
            smooth: true,
            emphasis: {
              focus: 'series'
            }
          },
          {
            name: '育苗中',
            type: 'line',
            data: statusData.inProgress,
            itemStyle: {
              color: '#E6A23C'
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0,
                  color: 'rgba(230,162,60,0.2)'
                }, {
                  offset: 1,
                  color: 'rgba(230,162,60,0)'
                }]
              }
            },
            smooth: true,
            emphasis: {
              focus: 'series'
            }
          },
          {
            name: '已完成',
            type: 'line',
            data: statusData.completed,
            itemStyle: {
              color: '#67C23A'
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0,
                  color: 'rgba(103,194,58,0.2)'
                }, {
                  offset: 1,
                  color: 'rgba(103,194,58,0)'
                }]
              }
            },
            smooth: true,
            emphasis: {
              focus: 'series'
            }
          }
        ]
      }
    }
  },
  created() {
    this.fetchNurseryOptions()
    // 如果有默认选中的育苗点，立即加载数据
    if (this.queryParams.deptId) {
      this.fetchStats()
    }
  },
  mounted() {
    // 监听窗口大小变化，重新渲染图表
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    // 移除事件监听
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    handleResize() {
      // 获取图表实例并重新渲染
      const chartComponent = this.$children.find(child => child.$options.name === 'EchartsCard')
      if (chartComponent && chartComponent.chart) {
        chartComponent.chart.resize()
      }
    },
    // 获取育苗点选项
    async fetchNurseryOptions() {
      try {
        const response = await request.get('/departments/page', {
          params: {
            deptType: 4, // 育苗点类型
            pageSize: 999 // 获取所有育苗点
          }
        })
        if (response && response.records) {
          this.nurseryOptions = response.records
        }
      } catch (error) {
        console.error('获取育苗点列表失败:', error)
        this.$message.error('获取育苗点列表失败')
      }
    },

    // 获取统计数据
    async fetchStats() {
      if (!this.queryParams.deptId) {
        this.$message.warning('请选择育苗点')
        return
      }

      try {
        this.loading = true
        const response = await request.get('/nursery-allocations/stats', {
          params: this.queryParams
        })
        this.allocationList = response
      } catch (error) {
        console.error('获取统计数据失败:', error)
        this.$message.error('获取统计数据失败')
      } finally {
        this.loading = false
      }
    },

    // 处理搜索
    handleSearch() {
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.startDate = this.dateRange[0]
        this.queryParams.endDate = this.dateRange[1]
      } else {
        this.queryParams.startDate = undefined
        this.queryParams.endDate = undefined
      }
      this.fetchStats()
    },

    // 重置查询
    resetQuery() {
      this.queryParams = {
        deptId: undefined,
        startDate: undefined,
        endDate: undefined
      }
      this.dateRange = []
      this.allocationList = []
    },

    // 获取状态对应的标签类型
    getStatusType(status) {
      const statusMap = {
        2: 'info',    // 已分配
        3: 'warning', // 育苗中
        4: 'success'  // 已完成
      }
      return statusMap[status] || ''
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  min-height: 100%;
  box-sizing: border-box;
  
  .filter-card {
    margin-bottom: 20px;

    :deep(.el-card__body) {
      padding: 20px;
    }
  }

  .stats-row {
    margin: 20px 0;

    .stats-card {
      text-align: center;
      padding: 20px;
      transition: all 0.3s;

      :deep(.el-card__body) {
        padding: 20px;
      }

      &:hover {
        transform: translateY(-5px);
      }

      .stats-title {
        font-size: 14px;
        color: #606266;
        margin-bottom: 10px;
      }

      .stats-value {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
      }
    }
  }

  .chart-card {
    margin: 20px 0;
    position: relative;
    z-index: 1;
    
    :deep(.el-card__body) {
      padding: 0;
      height: 100%;
    }
    
    .chart-wrapper {
      width: 100%;
      height: 400px;
      position: relative;
    }

    .echarts-container {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 2;
    }

    .no-data {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      text-align: center;
      color: #909399;
      z-index: 1;

      i {
        font-size: 48px;
        margin-bottom: 10px;
      }

      p {
        margin: 0;
        font-size: 14px;
      }
    }
  }

  .table-card {
    margin-top: 20px;

    :deep(.el-card__body) {
      padding: 20px;
    }
  }
}

.search-form {
  .el-form-item {
    margin-bottom: 0;
    margin-right: 10px;
  }
}
</style> 